<?php
declare (strict_types = 1);

namespace app\validate;

use think\Validate;

class CategoryValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id|栏目ID' => 'require|number',
        'parent_id|父级栏目ID' => 'require|integer',
        'module_id|模型' => 'requireIf:type,1|number',
        'title|栏目名称' => 'require|max:80',
        'type|栏目类型' => 'require|in:1,2,3,4',
        'list_tpl|列表模板' => 'requireListTpl',
        'lang|语言'   => 'require',
        'detail_tpl|详情模板' => 'requireDetailTpl',
        'sort|栏目排序' => 'number',
        'alias|别名' => 'requireAlias',
        'website_id|网站ID' => 'require|number',
        'site_id|网站ID' => 'require|array',
        'model_id|模型ID' => 'require|number'
    ];

    protected $scene = [
        'save' => ['parent_id','title','list_tpl','detail_tpl','alias','website_id','module_id','lang','alias'],
        'update' => ['id','parent_id','title','list_tpl','detail_tpl','alias','website_id','module_id','lang','alias'],
        'read'  => ['website_id','id'],
        'delete' => ['id','website_id','lang'],
        'getModuleCate' => ['site_id','lang','model_id']
    ];

    protected function requireAlias($value)
    {
        if(request()->param('type') == 1 || request()->param('type') == 4){
            $value = trim($value);
            if(strpos($value,'/') !== 0){
                return "别名请以'/'开头";
            }
            if(!preg_match('/[a-zA-Z0-9\-_\/]+$/',$value)){
                return "别名请用英文字母数字和'-,_,/'组合";
            }
            $lastStr = substr($value, -1);
            if(!preg_match('/[a-zA-Z0-9\/]+/',$lastStr)){
                return "别名请以英文字母或者数字结尾";
            }
        }
        if(request()->param('type') == 3){
            if(!filter_var($value,FILTER_VALIDATE_URL)){
                return '请输入正确的URL格式';
            }
        }
        return true;
    }

    protected function requireDetailTpl($value)
    {
        if(request()->param('type') == 1){
            if(empty($value)){
                return '详情页面模版不能为空';
            }
        }
        return true;
    }

    protected function requireListTpl($value)
    {
        if(in_array(request()->param('type'),[1,4])){
            if(empty($value)){
                return '列表页面模版不能为空';
            }
        }
        return true;
    }

}
